<template>
  <div class="app-container">
    <el-form :model="queryParams" ref="queryForm" :inline="true" v-show="showSearch" label-width="68px">
      <el-form-item label="节点名称" prop="projectName">
        <el-input
          v-model="queryParams.projectName"
          placeholder="请输入节点名称"
          clearable
          size="small"
          @keyup.enter.native="handleQuery"
        />
      </el-form-item>
      <el-form-item label="项目时限">
        <el-date-picker
          v-model="queryProjectDateRange"
          size="small"
          style="width: 240px"
          value-format="yyyy-MM-dd"
          type="daterange"
          range-separator="-"
          start-placeholder="开始日期"
          end-placeholder="结束日期"
        ></el-date-picker>
      </el-form-item>
      <el-form-item label="是否超时" prop="isTimeOut">
        <el-select v-model="queryParams.isTimeOut" placeholder="请选择是否超时" clearable size="small">
          <el-option
            v-for="dict in isTimeOutOptions"
            :key="dict.dictValue"
            :label="dict.dictLabel"
            :value="dict.dictValue"
          />
        </el-select>
      </el-form-item>
      <el-form-item label="里程碑" prop="isImportant">
        <el-select v-model="queryParams.isImportant" placeholder="请选择是否为里程碑节点" clearable size="small">
          <el-option
            v-for="dict in isImportantOptions"
            :key="dict.dictValue"
            :label="dict.dictLabel"
            :value="dict.dictValue"
          />
        </el-select>
      </el-form-item>
      <el-form-item label="责任部门" prop="deptName" class="item">
        <treeselect v-model="queryParams.deptId" clearable :options="deptOptions" :disable-branch-nodes="false" placeholder="请选择归属部门"  style="width:200px;" />
      </el-form-item>
      <el-form-item label="责任人" prop="userId">
          <treeselect v-model="queryParams.userId" :options="userTree" :disable-branch-nodes="true" :show-count="false" placeholder="请选择用户" style="width:200px;" />
      </el-form-item>
      <el-form-item>
        <el-button type="cyan" icon="el-icon-search" size="mini" @click="handleQuery">搜索</el-button>
        <el-button icon="el-icon-refresh" size="mini" @click="resetQuery">重置</el-button>
      </el-form-item>
    </el-form>

    <el-row :gutter="10" class="mb8">
      <el-col :span="1.5">
        <el-button
          type="primary"
          icon="el-icon-plus"
          size="mini"
          @click="handleAdd"
          v-hasPermi="['project:project:add']"
        >新增阶段</el-button>
      </el-col>
      <el-col :span="1.5">
        <el-button
          type="warning"
          icon="el-icon-download"
          size="mini"
          @click="handleExport"
          v-hasPermi="['project:project:export']"
        >导出</el-button>
      </el-col>
	  <right-toolbar :showSearch.sync="showSearch" @queryTable="getList"></right-toolbar>
    </el-row>

    <el-table
        v-loading="loading"
        :data="projectList"
        row-key="projectId"
        default-expand-all
        :tree-props="{children: 'children', hasChildren: 'hasChildren'}"
        border style="width: 100%"
        height="600"
        :row-class-name="tableRowClassName"
      >
      <el-table-column type="selection" width="55" align="center" v-if="false"/>
      <el-table-column label="节点名称" align="left" prop="projectName" fixed/>
      <!-- <el-table-column label="项目令号" align="center" prop="projectCode" width="180"/>
      <el-table-column label="年限" align="center" prop="projectTime" /> -->
      <!-- <el-table-column label="项目类型" align="center" prop="projectType" :formatter="projectTypeFormat" width="180" /> -->
      <el-table-column label="开始时间" align="center" prop="startTime" width="120">
        <template slot-scope="scope">
          <span>{{ parseTime(scope.row.startTime, '{y}-{m}-{d}') }}</span>
        </template>
      </el-table-column>
      <el-table-column label="结束时间" align="center" prop="finishTime" width="120">
        <template slot-scope="scope">
          <span>{{ parseTime(scope.row.finishTime, '{y}-{m}-{d}') }}</span>
        </template>
      </el-table-column>
      <el-table-column label="完成时间" align="center" prop="relFinishTime" width="120">
        <template slot-scope="scope">
          <span>{{ parseTime(scope.row.relFinishTime, '{y}-{m}-{d}') }}</span>
        </template>
      </el-table-column>
      <el-table-column label="是否超时123" align="center" prop="isTimeOut" :formatter="isTimeOutFormat" width="40"/>
      <!-- <el-table-column label="里程碑" align="center" prop="isImportant" :formatter="isImportantFormat" /> -->
      <el-table-column label="审核人" align="center" prop="technologyLeader" width="80"/>
      <!-- <el-table-column label="负责人" align="center" prop="nickName" width="80"/> -->
      <el-table-column label="状态" align="center" prop="state" :formatter="stateFormat" width="40"/>
      <el-table-column label="操作" align="center" class-name="small-padding fixed-width" width="250" fixed="right">
        <template slot-scope="scope">
          <el-button
            size="mini"
            type="text"
            icon="el-icon-plus"
            @click="handleAdd(scope.row)"
            v-hasPermi="['project:project:add']"
          >新增阶段</el-button>
           <el-button
            size="mini"
            type="text"
            icon="el-icon-unlock"
            @click="handleResolve(scope.row)"
            v-hasPermi="['project:project:resolve']"
          >新增工作</el-button>
          <el-button
            size="mini"
            type="text"
            icon="el-icon-upload2"
            @click="handleFileUpload(scope.row)"
            v-hasPermi="['project:project:file']"
          >上传附件</el-button>
           <el-button
            size="mini"
            type="text"
            icon="el-icon-tickets"
            @click="handleDetails(scope.row)"
            v-hasPermi="['project:user:details']"
          >工作详情</el-button>
          <el-button
            size="mini"
            type="text"
            icon="el-icon-edit"
            @click="handleUpdate(scope.row)"
            v-hasPermi="['project:project:edit']"
          >修改阶段</el-button>
          <el-button
            size="mini"
            type="text"
            icon="el-icon-delete"
            @click="handleDelete(scope.row)"
            v-hasPermi="['project:project:remove']"
          >删除阶段</el-button>

        </template>
      </el-table-column>
    </el-table>
    
    <pagination
      v-show="total>0"
      :total="total"
      :page.sync="queryParams.pageNum"
      :limit.sync="queryParams.pageSize"
      @pagination="getList"
    />

    <!-- 添加或修改项目管理对话框 -->
    <el-dialog :title="title" :visible.sync="open" width="800px" :close-on-click-modal="false" append-to-body>
      <el-form ref="form" :model="form" :rules="rules" label-width="100px">
      <el-row :gutter="10">
        <el-col :span="24">
          <el-form-item label="上级节点" prop="parentId">
              <treeselect v-model="form.parentId" :options="projectTreeOptions" :disable-branch-nodes="false" :show-count="true" placeholder="请选择上级节点" />
          </el-form-item>
        </el-col>
        <el-col :span="24">
          <el-form-item label="节点名称" prop="projectName">
            <el-input v-model="form.projectName"  placeholder="请输入项目名称" />
          </el-form-item>
        </el-col>
        <el-col :span="12">
          <el-form-item label="开始时间" prop="startTime">
            <el-date-picker clearable size="small" style="width:100%"
              v-model="form.startTime"
              type="date"
              value-format="yyyy-MM-dd"
              placeholder="选择开始时间">
            </el-date-picker>
          </el-form-item>
        </el-col>
        <el-col :span="12">
          <el-form-item label="结束时间" prop="finishTime">
            <el-date-picker clearable size="small" style="width:100%"
              v-model="form.finishTime"
              @change="checkTime"
              type="date"
              value-format="yyyy-MM-dd"
              placeholder="选择结束时间">
            </el-date-picker>
          </el-form-item>
        </el-col>
        <el-col :span="12">
          <el-form-item label="人员选择" prop="isUser">
            <el-radio-group v-model="form.isUser" @change="isUserChange">
              <el-radio v-for="item in isUserTeamOptions" :key="item.value" :label="item.label" :value="item.value"></el-radio>
            </el-radio-group>
          </el-form-item>  
        </el-col>
        <el-col :span="12">
          <el-form-item label="审核人" prop="technologyLeaderUserId" v-if="isTeamUser">
            <el-select v-model="form.technologyLeaderUserId" @change="setCheckProcess" filterable placeholder="请选择项目成员角色" clearable style="width:100%">
              <el-option
                v-for="team in projectTeamUserOptions"
                :key="team.teamId"
                :label="team.nickName"
                :value="team.userId">
              <span style="float: left">{{ team.nickName }}</span>
              <span style="float: right; color: #8492a6; font-size: 13px">{{ team.roleName }}</span>
              </el-option>
            </el-select>
          </el-form-item>
          <el-form-item label="审核人" prop="technologyLeaderUserId" v-if="isTreeUser">
            <treeselect v-model="form.technologyLeaderUserId" :options="userTree" :multiple="false"
            :disable-branch-nodes="true" :show-count="false" 
            placeholder="请选择用户"  @select="setUserTreeCheckProcess" style="width:100%"/>
          </el-form-item>
        </el-col>
        
      </el-row>
      </el-form>
      <div slot="footer" class="dialog-footer">
        <el-button type="primary" @click="submitForm">确 定</el-button>
        <el-button @click="cancel">取 消</el-button>
      </div>
    </el-dialog>

     
    <!-- 分解人员对话框 -->
    <el-dialog :title="resolve.title" :visible.sync="resolve.open" width="1000px" :close-on-click-modal="false" append-to-body>
      <el-form ref="resolve.form" :model="resolve.form" :rules="resolve.rules" label-width="80px">
        <el-row>
          <el-col :span="24">
            <el-form-item label="人员选择" prop="isUser">
              <el-radio-group v-model="resolve.form.isUser" @change="isUserChange">
                <el-radio v-for="item in isUserTeamOptions" :key="item.value" :label="item.label" :value="item.value"></el-radio>
              </el-radio-group>
            </el-form-item>  
          </el-col>
          <el-col :span="8">
            <el-form-item label="负责人" prop="userId" v-if="isTeamUser">
              <el-select v-model="resolve.form.userId" @change="setFileHoursList" placeholder="请选择项目成员角色" clearable style="width:100%">
                <el-option
                  v-for="team in projectTeamUserOptions"
                  :key="team.teamId"
                  :label="team.nickName"
                  :value="team.userId"
                >
                <span style="float: left">{{ team.nickName }}</span>
                <span style="float: right; color: #8492a6; font-size: 13px">{{ team.roleName }}</span>
                </el-option>
              </el-select>
            </el-form-item>
            <el-form-item label="负责人" prop="userId" v-if="isTreeUser" >
              <treeselect v-model="resolve.form.userId" :options="userTree" :multiple="false"
              :disable-branch-nodes="true" :show-count="false" 
              placeholder="请选择用户" style="width:100%" @select="userTreeFileHoursList"/>
            </el-form-item>
          </el-col>
          <el-col :span="8">
            <el-form-item prop="fileId" label="工作时长">
              <el-select v-model="resolve.form.fileId" clearable  style="width:100%">
                <el-option v-for="item in filesOptions" :key="item.fileId" :label="item.name" :value="item.fileId" :disabled="item.state == 1" ></el-option>
              </el-select>
            </el-form-item>
          </el-col>
          <el-col :span="8">
            <el-form-item label="所属组别" prop="workUserGroup">
              <el-select v-model="resolve.form.workUserGroup"  filterable  placeholder="请选择" prop="groups" style="width:100%">
                <el-option v-for="item in groupTypeOptions" :key="item.id" :label="item.name" :value="item.code" :disabled="item.states == 1"></el-option>
              </el-select>
            </el-form-item>
          </el-col>
          
          <el-col :span="24">
            <el-form-item label="工作内容" prop="workContent" >
              <el-input v-model="resolve.form.workContent" type="textarea" placeholder="请输入内容" />
            </el-form-item>
          </el-col>
          <el-col :span="8">
            <el-form-item label="开始时间" prop="startTime">
              <el-date-picker clearable size="small"  style="width:100%"
                v-model="resolve.form.startTime"
                type="date"
                :default-value="resolve.form.startTime"
                value-format="yyyy-MM-dd"
                placeholder="选择开始时间">
              </el-date-picker>
            </el-form-item>
          </el-col>
          <el-col :span="8">
            <el-form-item label="结束时间" prop="finishTime">
              <el-date-picker clearable size="small"  style="width:100%"
                v-model="resolve.form.finishTime"
                type="date"
                :default-value="resolve.form.finishTime"
                value-format="yyyy-MM-dd"
                 @change="checkResolveTime"
                placeholder="选择结束时间">
              </el-date-picker>
            </el-form-item>
          </el-col>
          <el-col :span="8">
            <el-form-item label="是否输出" prop="isSubmitFile" >
              <el-radio-group v-model="resolve.form.isSubmitFile"  @change="isSubmitFileChange">
                <el-radio v-for="dict in isSubmitFileOptions" :key="dict.dictValue" :label="dict.dictValue">{{dict.dictLabel}}</el-radio>
              </el-radio-group>
            </el-form-item>
          </el-col>
          <el-col :span="16">
            <el-form-item label="输出物名" prop="submitName">
              <el-input v-model="resolve.form.submitName" placeholder="请输入输出物名称" />
            </el-form-item>
          </el-col>
          <el-col :span="8">
            <el-form-item label="审核人" prop="checkUserId">
                <treeselect v-model="resolve.form.checkUserId" :options="userTree" :multiple="false"
                :disable-branch-nodes="true" :show-count="false" 
                placeholder="请选择审核人" style="width:100%"/>
            </el-form-item>
          </el-col>
            <!-- <el-col :span="6">
              <el-button 
                type="success" 
                icon="el-icon-circle-plus-outline" 
                size="medium" 
                circle
                @click="addRow()">
              </el-button>
              <el-button
                type="danger"
                icon="el-icon-delete"
                circle
                size="medium"
                @click="removeRow()"
              ></el-button>
            </el-col> -->
            <el-col :span="24"  v-if="resolve.isPeopleWorkLineShow" >
                <AnalyzeEasyLineCharts class="middleTwo" :handleOfficeLineCharts="handlePeopleLineCharts" :chart-data="peopleCompositeLineCharts" />
          </el-col>
        </el-row>
      </el-form>
      <div slot="footer" class="dialog-footer">
        <el-button type="primary" @click="submitResolveForm">确 定</el-button>
        <el-button @click="cancelResolve">取 消</el-button>
      </div>
    </el-dialog>

    <!-- 上传文件 -->
     <el-dialog :title="upload.title" :visible.sync="upload.open" :close-on-click-modal="false"  width="800px" append-to-body>
      <el-tabs v-model="upload.activeName">
        <el-tab-pane id="fileUpload" label="上传" name="first">
              <el-upload ref="upload" 
              :headers="upload.headers" 
              :limit="1" 
              :data="upload.data"
              :action="upload.url" 
              :disabled="upload.isUploading" 
              :on-progress="handleFileUploadFile" 
              :on-success="handleFileSuccess" 
              :auto-upload="false" drag>
              <i class="el-icon-upload"></i>
              <div class="el-upload__text">
                将文件拖到此处，或
                <em>点击上传</em>
              </div>
            </el-upload>
          <el-button type="primary" @click="submitFileForm" style="display:block;margin:0 auto;marginTop:1em">上 传</el-button>
        </el-tab-pane>
        <el-tab-pane label="附件查看" name="second">
            <el-row :gutter="10" class="mb8">
            </el-row>
            <el-table v-loading="loading" :data="upload.fileLists" border @selection-change="handleSelectionFileChange">
                  <el-table-column type="selection" width="55" align="center" />
                  <el-table-column label="文件ID" align="center" prop="id" v-if="false"/>
                  <el-table-column label="文件URL" align="center" prop="url" v-if="false"/>
                  <el-table-column label="文件名称" align="center" prop="name"/>
                  <el-table-column label="文件类型" align="center" prop="type" :formatter="stateFileTypeFormat" />
                  <el-table-column label="操作" align="center" class-name="small-padding fixed-width">
                    <template slot-scope="scope">
                      <el-button
                        size="mini"
                        type="text"
                        icon="el-icon-edit"
                        @click="handleFileDownload(scope.row)"
                      >下载</el-button>
                      <el-button
                        size="mini"
                        type="text"
                        icon="el-icon-delete"
                        @click="handleFileDelete(scope.row)"
                        v-hasPermi="['project:project:fileremove']"
                      >删除</el-button>
                    </template>
                  </el-table-column>
            </el-table>
        </el-tab-pane>
      </el-tabs>
      <div slot="footer" class="dialog-footer">
        <!-- <el-button type="primary" @click="submitFileForm">确 定</el-button> -->
        <el-button @click="upload.open = false">取 消</el-button>
      </div>
    </el-dialog>
  </div>
</template>
<script>
import AnalyzeEasyLineCharts from '../../../statistics/linecharts/AnalyzeEasyLineChart';
import { listProjectTree, getProject, delProject, addProject, updateProject, exportProject, projectTreeselect, selectFiles, deleteFiles, listHours} from "@/api/project/projectTree";
import { getTeamUser } from "@/api/project/team";
import { queryPeopleCompositeTotalLineCharts } from "@/api/statistics/work/composite";
import echarts from 'echarts';
import {addProcessAndResolve} from "@/api/work/user";
import {getToken } from "@/utils/auth";
import {groupList} from "@/api/work/process";
import {getUserTree} from "@/api/trialproduce/car";
import { treeselect } from "@/api/system/dept";
import Treeselect from "@riophae/vue-treeselect";
import "@riophae/vue-treeselect/dist/vue-treeselect.css";

export default {
  name: "Project",
  components: {
     Treeselect,
     AnalyzeEasyLineCharts
  },
  data() {
    return {
      //基础路径
      baseURL : process.env.VUE_APP_BASE_API,
      // 遮罩层
      loading: true,
      // 选中数组
      ids: [],
      // 非单个禁用
      single: true,
      // 非多个禁用
      multiple: true,
      // 显示搜索条件
      showSearch: true,
      // 总条数
      total: 0,
      // 项目管理表格数据
      projectList: [],
      // 弹出层标题
      title: "",
      // 是否显示弹出层
      open: false,
      // 项目类型字典
      projectTypeOptions: [],
      // 部门树选项
      deptOptions: [],
      // 项目树选项
      projectTreeOptions : undefined,
      // 是否超时字典
      isTimeOutOptions: [],
      // 是否为里程碑节点字典
      isImportantOptions: [],
      //组别
      groupTypeOptions: [],
      // 文件时长选项
      filesOptions:[],
       //文件类型
      textFileTypeOptions: [],
      //是否输出
      isSubmitFileOptions:[],
      //状态
      stateOptions: [],
       //查询时间控件
      queryProjectDateRange: [],
      //项目组成员
      projectTeamUserOptions: [],
      //用户数结构
      userTree:[],
      //项目组用户
      isTeamUser: true,
      //中心用户
      isTreeUser: false,

      //是否为新增
      isAdd: true,
      //选择用户
      isUserTeamOptions:[
        { 
          value: '0',
          label: '全部'
        },
        {
          value: '1',
          label: '项目组'
        }
      ],
      //人员近30天工作
      peopleCompositeLineCharts:{},
      // 查询参数
      queryParams: {
        pageNum: 1,
        pageSize: 10,
        projectName: null,
        projectCode: null,
        projectTime: null,
        projectType: null,
        startTime: null,
        isTimeOut: null,
        isImportant: null,
        deptId: null,
        userId: null,
        relParentId: null,
      },
      // 查询树参数
      queryTreeParams: {
        relParentId: null
      },
      // 表单参数
      form: {
        
      },
      // 表单校验
      rules: {
        projectName: [
          { required: true, message: "节点名称不能为空", trigger: "blur" }
        ],
        parentId: [
          { required: true, message: "父级节点不能为空", trigger: "blur" }
        ],
        startTime: [
          { required: true, message: "开始时间不能为空", trigger: "blur" }
        ],
        finishTime: [
          { required: true, message: "结束时间不能为空", trigger: "blur" }
        ],
        isImportant: [
          { required: true, message: "里程碑不能为空", trigger: "blur" }
        ],
        deptId: [
          { required: true, message: "责任部门不能为空", trigger: "blur" }
        ],
        userId: [
          { required: true, message: "项目经理不能为空", trigger: "blur" }
        ],
        technologyLeaderUserId: [
          { required: true, message: "审核人不能为空", trigger: "blur" }
        ],
        fileId: [
          { required: true, message: "工作时长不能为空", trigger: "blur" }
        ],
      },
      //分解人员工作参数
      resolve :{
          //是否显示人员统计
          isPeopleWorkLineShow: false,
          query: {
            projectId:null
          },
          form :{
            projectId: null,
            startTime: null,
            finishTime: null
          },
          //查询统计图参数
          queryTotal:{
              userId: null,
              beginTime: null,
              endTime: null
          },
          title: undefined,
          open : false,
          rules: {
            userId: [
              { required: true, message: "责任人不能为空", trigger: "blur" }
            ],
            fileId: [
              { required: true, message: "工作时长不能为空", trigger: "blur" }
            ],
            userGroup: [
              { required: true, message: "所属组别不能为空", trigger: "blur" }
            ],
            startTime: [
              { required: true, message: "开始时间不能为空", trigger: "blur" }
            ],
            finishTime: [
              { required: true, message: "结束时间不能为空", trigger: "blur" }
            ],
            isSubmitFile: [
              { required: true, message: "是否输出不能为空", trigger: "blur" }
            ],
            submitName: [
              { required: true, message: "输出物名不能为空", trigger: "blur" }
            ],
            workContent: [
              { required: true, message: "工作内容不能为空", trigger: "blur" }
            ],
            checkUserId: [
               { required: true, message: "审核人不能为空", trigger: "blur" }
            ]
          }
      },
      upload: {
        title: null,
        open: false,
        // 上传标签页
        activeName: 'first',
        // 设置上传的请求头部
        headers: { Authorization: 'Bearer ' + getToken()},
        // 是否禁用上传
        isUploading: false,
        // 上传的地址
        url: process.env.VUE_APP_BASE_API+"/project/project/tree/upload",
        //路径
        baseURL:  process.env.VUE_APP_BASE_API,
        // 设置上传的请求头部
        headers: { Authorization: 'Bearer ' + getToken()},
        data: {
          tableId: null
        },
        //总数
        total: 0,
        fileLists: [{
          id:'',
          url: "",
          name: '',
          type: ''
        }],
      },
      apply: {
        title:"",
        open: false,
        form:{
          tableId:"",
          tableName:"0",
          checkList:[]
        }
      },
      //审核人ID
      checkUserId: null,
      //审核流程
      progresses: [],
    };
  },
  created() {
    const relParentId = this.$route.params && this.$route.params.projectId;
    this.queryParams.relParentId = relParentId;
    this.queryTreeParams.relParentId = relParentId;
    this.resolve.query.projectId = relParentId;
    this.getList();
    this.getTreeselect();
    this.getProjectTreeselect();
    this.handleGroupList();
    this.handleUserTree();
    this.handleTeamUserList();
    this.getDicts("pm_project_type").then(response => {
      this.projectTypeOptions = response.data;
    });
    this.getDicts("sys_yes_no").then(response => {
      this.isTimeOutOptions = response.data;
    });
    this.getDicts("sys_yes_no").then(response => {
      this.isImportantOptions = response.data;
    });
    this.getDicts("sys_file_type").then(response => {
      this.textFileTypeOptions = response.data;
    });
    this.getDicts("sys_yes_no").then(response => {
      this.isSubmitFileOptions = response.data;
    });
    this.getDicts("work_file_state").then(response => {
      this.stateOptions = response.data;
    });
  },
  methods: {
    //用户树
    handleUserTree(){
      getUserTree().then(response => {
        this.userTree = response.data;
      });
    },
    //工作时长
    getFilesList(userId){
      listHours(userId).then((response) => {
        this.filesOptions = response.data;
      });
    },
    // 查询组别
    handleGroupList(){
      groupList().then((response) => {
        this.groupTypeOptions = response.data;
      });
    },
    /** 查询项目下拉树结构 */
    getProjectTreeselect() {
      projectTreeselect(this.queryTreeParams).then((response) => {
        this.projectTreeOptions = response.data;
      });
    },
    /** 查询部门下拉树结构 */
    getTreeselect() {
      treeselect().then((response) => {
        this.deptOptions = response.data;
      });
    },
    /** 查询项目管理列表 */
    getList() {
      this.loading = true;
      listProjectTree(this.addQueryParamsDateRange(this.queryParams)).then(response => {
        this.projectList = this.handleTree(response.data, "projectId");
        this.loading = false;
      });
    },
     /** 转换部门数据结构 */
    normalizer(node) {
      if (node.children && !node.children.length) {
        delete node.children;
      }
      return {
        id: node.deptId,
        label: node.deptName,
        children: node.children
      };
    },
    // 项目类型字典翻译
    projectTypeFormat(row, column) {
      return this.selectDictLabel(this.projectTypeOptions, row.projectType);
    },
    // 是否超时字典翻译
    isTimeOutFormat(row, column) {
      return this.selectDictLabel(this.isTimeOutOptions, row.isTimeOut);
    },
    // 是否为里程碑节点字典翻译
    isImportantFormat(row, column) {
      return this.selectDictLabel(this.isImportantOptions, row.isImportant);
    },
    // 文件类型翻译
    stateFileTypeFormat(row, column) {
      return this.selectDictLabel(this.textFileTypeOptions, row.type);
    },
     // 任务状态翻译
    stateFormat(row, column) {
      return this.selectDictLabel(this.stateOptions, row.state);
    },
    // 取消按钮
    cancel() {
      this.open = false;
      this.reset();
    },
    // 表单重置
    reset() {
      this.form = {
        projectId: null,
        parentId: null,
        ancestors: null,
        projectName: null,
        projectCode: null,
        projectTime: null,
        projectType: null,
        startTime: null,
        finishTime: null,
        relFinishTime: null,
        isTimeOut: 'N',
        isImportant: 'N',
        deptId: null,
        userId: null,
        createTime: null,
        updateTime: null,
        createBy: null,
        updateBy: null,
        isUser: "项目组"
      };
      this.isTeamUser = true;
      this.isTreeUser = false;
      this.resetForm("form");
    },
    // 分解表单重置
    resetResolve() {
      this.resolve.form = {
        userId: null,
        workTime: null,
        userGroup: null,
        startTime: null,
        finishTime: null,
        isSubmitFile: 'Y',
        isUser: "项目组"
      };
      this.isTeamUser = true;
      this.isTreeUser = false;
      this.filesOptions =[];
      this.resetForm("resolve.form");
    },
    /** 搜索按钮操作 */
    handleQuery() {
      this.queryParams.pageNum = 1;
      this.getList();
    },
    /** 重置按钮操作 */
    resetQuery() {
      this.queryProjectDateRange = [];
      this.queryParams.deptId = null;
      this.resetForm("queryForm");
      this.handleQuery();
    },
    // 多选框选中数据
    handleSelectionChange(selection) {
      this.ids = selection.map(item => item.projectId)
      this.single = selection.length!==1
      this.multiple = !selection.length
    },
    /** 新增按钮操作 */
    handleAdd(row) {
      this.reset();
      this.getProjectTreeselect();
      const projectId = row.projectId;
      if (row != undefined) {
        this.form.parentId = projectId;
      }
      this.open = true;
      this.title = "添加项目管理";
    },
    /** 修改按钮操作 */
    handleUpdate(row) {
      this.reset();
      const projectId = row.projectId || this.ids
      if(row.parentId==0){
          this.$message({
            showClose: true,
            message: '顶级节点不允许修改。',
            type: 'warning'
          });
          return;
      }
      getProject(projectId).then(response => {
        this.form = response.data;
        this.open = true;
        this.title = "修改项目管理";
      });
    },
    /** 提交按钮 */
    submitForm() {
      this.$refs["form"].validate(valid => {
        if (valid) {
          if (this.form.projectId != null) {
            updateProject(this.form).then(response => {
              if (response.code === 200) {
                this.msgSuccess("修改成功");
                this.open = false;
                this.getList();
              }
            });
          } else {
            this.form.workType = 2;

            addProject(this.form).then(response => {

              if (response.code === 200) {
                this.msgSuccess("新增成功");
                this.open = false;
                this.getList();
              }
            });
          }
        }
      });
    },
    /** 删除按钮操作 */
    handleDelete(row) {
      const projectIds = row.projectId || this.ids;
      this.$confirm('是否确认删除项目管理编号为"' + projectIds + '"的数据项?', "警告", {
          confirmButtonText: "确定",
          cancelButtonText: "取消",
          type: "warning"
        }).then(function() {
          return delProject(projectIds);
        }).then(() => {
          this.getList();
          this.msgSuccess("删除成功");
        }).catch(function() {});
    },
    /** 导出按钮操作 */
    handleExport() {
      const queryParams = this.queryParams;
      this.$confirm('是否确认导出所有项目管理数据项?', "警告", {
          confirmButtonText: "确定",
          cancelButtonText: "取消",
          type: "warning"
        }).then(function() {
          return exportProject(queryParams);
        }).then(response => {
          this.download(response.msg);
        }).catch(function() {});
    },
     // 分解操作
    handleResolve(row){
      this.resetResolve();
      this.resolve.form.workId = row.projectId;
      this.resolve.form.startTime = row.startTime;
      this.resolve.form.finishTime = row.finishTime;
      this.$set(this.resolve.form,"startTime",row.startTime);
      this.$set(this.resolve.form,"finishTime",row.finishTime);
      this.resolve.open = true;
      this.resolve.isPeopleWorkLineShow = false;
      this.peopleCompositeLineCharts = {};
      this.resolve.form.workType = "1";
      this.resolve.title = "分解任务";
    },
    // 提交分解表单
    submitResolveForm(){
      this.$refs["resolve.form"].validate(valid => {
        this.resolve.form.workType = 1;
        if (valid) {
            addProcessAndResolve(this.resolve.form).then(response => {
              if (response.code === 200) {
                this.msgSuccess("分解成功");
                this.resolve.open = false;
              }
            });
            this.getList();
          }
      }); 
    },
    // 取消分解表单按钮
    cancelResolve() {
      this.resolve.open = false;
      this.reset();
    },
    /** 附件上传按钮操作 */
    handleFileUpload(row) {
      const projectIds = row.projectId;
      this.upload.title = "上传附件";
      this.upload.open = true;
      this.upload.data.tableId = projectIds;
      this.getFileList();
    },
    // 附件上传中处理
    handleFileUploadFile(event, file, fileList) {
      this.upload.isUploading = true;
    },
    // 附件上传成功处理
    handleFileSuccess(response, file, fileList) {
      this.upload.open = true;
      this.upload.isUploading = false;
      this.$refs.upload.clearFiles();
      this.$alert(response.msg, "上传结果", { dangerouslyUseHTMLString: true });
      this.getFileList();
      this.getList();
    },
    // 附件提交上传文件
    submitFileForm() {
      this.$refs.upload.submit();
    },
     //附件列表
    handleSelectionFileChange(selection){
      this.id = selection.map(item => item.id)
      this.uri = selection.map(item => item.uri)
      this.single = selection.length!==1
      this.multiple = !selection.length
    },
    /** 查询附件列表 */
    getFileList() {
      this.loading = true;
      selectFiles(this.upload.data.tableId).then((response) => {
        this.upload.fileLists = response.rows;
        this.upload.total = response.total;
        this.loading = false;
      });
    },
    // 删除文件操作
    handleFileDelete(row){
      const id = row.id || this.id;
      this.$confirm('是否确认删除任务分配编号为"' + id + '"的数据项?', "警告", {
          confirmButtonText: "确定",
          cancelButtonText: "取消",
          type: "warning"
        }).then(function() {
          return deleteFiles(id);
        }).then(() => {
          this.getFileList();
          this.msgSuccess("删除成功");
        }).catch(function() {});
    },
    // 下载文件
    handleFileDownload(row){
      const id = row.id || this.id;
      const url = row.uri || this.uri;
      window.location.href = this.baseURL+url;
    },
     /** 详情按钮操作 */
    handleDetails(row) {
      if(null!=row.projectId&&row.projectId!=''&row.projectId!=undefined){
          this.$router.push({
            path:'/project/user/'+row.projectId,     
            query:{
              parentId:this.resolve.query.projectId,
              deptId:row.deptId,
              startTime: row.startTime,
              finishTime: row.finishTime,
              projectName: row.projectName
            }
          })
      }else{
         this.msgError("浏览器错误，请刷新后重试");
      }
    },
   isSubmitFileChange(value){
      if('Y'==value){
          this.resolve.rules.submitName[0].required = true;
      }else{
          this.resolve.rules.submitName[0].required = false;
      }
   },
   //校验时间是否符合要求
    checkTime(value){
      console.log("结束时间");
        if(null == this.form.startTime){
            this.form.finishTime = null;
            this.$message({
              showClose: true,
              message: '请选择开始时间',
              type: 'warning'
            });
        }else{
             var result = this.compareTime(this.form.startTime,value)
             if(result==false){
                this.$message({
                  showClose: true,
                  message: '结束时间不能小于开始时间',
                  type: 'warning'
                });
                this.form.finishTime = null;
             }
        }
    },
    //分解表单时间限制
    checkResolveTime(value){
        if(null == this.resolve.form.startTime){
            this.resolve.form.finishTime = null;
            this.$message({
              showClose: true,
              message: '请选择开始时间',
              type: 'warning'
            });
        }else{
             var result = this.compareTime(this.resolve.form.startTime,value)
             if(result==false){
                this.$message({
                  showClose: true,
                  message: '结束时间不能小于开始时间',
                  type: 'warning'
                });
                this.resolve.form.finishTime = null;
             }else{
               this.queryPeopleWorkLine();
             }
        }
    },
    //查询人员工作曲线图
    queryPeopleWorkLine(){
      if(null==this.resolve.form.userId){
            this.$message({
              showClose: true,
              message: '请选人人员信息',
              type: 'warning'
            });
            return;
      }
      if(null==this.resolve.form.startTime||"" == this.resolve.form.startTime){
            this.$message({
              showClose: true,
              message: '请选择开始时间',
              type: 'warning'
            });
            return;
      }
      if(null==this.resolve.form.finishTime||"" == this.resolve.form.finishTime){
            this.$message({
              showClose: true,
              message: '请选择结束时间',
              type: 'warning'
            });
            return;
      }
      this.resolve.queryTotal.userId = this.resolve.form.userId;
      this.resolve.queryTotal.beginTime = this.resolve.form.startTime;
      this.resolve.queryTotal.endTime = this.resolve.form.finishTime;
      this.handlePeopleLineCharts(this.resolve.queryTotal);
      this.resolve.isPeopleWorkLineShow = true;
    },
    //比较时间大小
    compareTime(start,end){
      let startDate = new Date(start);
      let endDate = new Date(end);
      if (endDate >= startDate) {
        return true
      } else {
        return false
      }
    },
    //时间控件转换时间字段
    addQueryParamsDateRange(queryParams){
        this.queryProjectDateRange;
        this.queryParams.beginTime =  this.queryProjectDateRange[0];
        this.queryParams.endTime =  this.queryProjectDateRange[1];
        return queryParams;
    },
     // 查看项目组成员信息
    handleTeamUserList(){
      this.projectTeamUserOptions = [];
      getTeamUser(this.resolve.query).then((response) => {
        this.projectTeamUserOptions = response.data;
      });
    },
    //设置用户选择权限
    isUserChange(value){
       this.filesOptions =[];
       this.resolve.form.userId = null;
       this.form.userId = null;
       if('全部'==value){
          this.isTeamUser = false;
          this.isTreeUser = true;
      }else{
          this.isTeamUser = true;
          this.isTreeUser = false;
      }
    },
    
    //修改列颜色
    tableRowClassName({row, rowIndex}) {
        if (row.isTimeOut === 'Y') {
          return 'danger-row';
        } else{
          return 'success-row';
        }
    },
    // 查询人员最近30天工作曲线
    handlePeopleLineCharts(params){
        let userName = "";
        queryPeopleCompositeTotalLineCharts(params).then(response => {
            let newObject = {
                xdata:[],
                ydata:[],
                zdata:[],
                adata:[],
                bdata:[]
            }  
            response.forEach((item,index)=>{
                newObject.xdata.push(item.time)
                newObject.ydata.push(item.totalValue)
                userName = item.name;
            })
            newObject.bdata.push(userName+":近30天工作量曲线（H）");
            this.peopleCompositeLineCharts = newObject
        });
    },
    //监听下拉选择用户接口
    setCheckProcess(value){
      this.getFilesList(value);
    },
    //监听树型选择用户接口
    setUserTreeCheckProcess(value){
        this.getFilesList(value.id);
    },
    //设置文件工时参数
    setFileHoursList(value){
      this.getFilesList(value);
      this.queryPeopleWorkLine();
    },
     //设置文件工时参数
    userTreeFileHoursList(value){
      this.resolve.form.userId = value.id;
      this.getFilesList(value.id);
      this.queryPeopleWorkLine();
    },
    //打开审核页面
    openCheckView(row){
      const projectId = row.projectId;
      this.apply.form.tableId = projectId;
      this.resetProcess();
      this.progresses.push(
        {
          title:"申请人",
          date: this.form.nickName,
          id: row.userId,
          type :0,
          index: 0

        }
      )
    },
    //增加审核人
    addRow() {
      this.checkUserId = null;
      let date = this.progresses[this.progresses.length-1].date;
      if(date == null ||date ==""){
          this.$message({
            showClose: true,
            message: '请选择审核人员！',
            type: 'warning'
          });
          return;
      }else{
          let len = this.progresses.length;
          this.progresses.push(
            {
              title:"审核人",
              id:"",
              date:"",
              type :1,
              index: len
            }
          );
      }
    },
    // 删除审核人
    removeRow() {
      if(this.progresses.length<=1){
          this.$message({
            showClose: true,
            message: '没有可删除的审核人！',
            type: 'warning'
          });
          return;
      }else{
        let index = this.progresses.length-1;
        this.progresses.splice(index,1);
      }
    },
  }
};
</script>

<style>
.el-upload-list__item-name{
    font-size: 16px;
}
#fileUpload .el-upload-dragger{
  display:block;
  margin:0 auto;
  margin-top:1em;
  width: 760px;
  height: 180px;
}
.el-table .warning-row {
  background: rgb(151, 198, 252);
}

.el-table .success-row {
  background: #c6ee99;
}

.el-table .danger-row {
  background: #f8b690;
}

</style>
